<template>
  <layout-drawer-list v-model:visible="visible" :title="enumModifyType(drawerType)">
    <template #main>
      <div>
        <div>
          <a-radio-group v-model:value="subjectId" @change="changeSubjectId">
            <a-radio-button v-for="item in ['1', '2']" :key="item" :value="item">{{enumSubjectId(item)}}</a-radio-button>
          </a-radio-group>
        </div>
        <vxe-toolbar>
          <template #buttons>
            <a-button type="primary" @click="openDrawer('create')">新增</a-button>
          </template>
          <template #tools></template>
        </vxe-toolbar>
      </div>
      <div class="rd-flex-1">
        <vxe-grid v-bind="gridOptions" :data="tableTree">
          <template #icon="{ row }">
            <IconAntdv :icon="row.icon" />
          </template>
          <template #type="{ row }">
            <span>{{ enumMenuType(row.type) }}</span>
          </template>
          <template #modify="{ row }">
            <a-button type="link" size="small" @click="openDrawer('edit', row)">编辑</a-button>
            <a-popconfirm
              title="删除该节点前确保节点下无子节点，是否删除？"
              ok-text="删除"
              cancel-text="取消"
              @confirm="onSubmitDelete(row)"
            >
              <a href="#">删除</a>
            </a-popconfirm>
          </template>
          <!-- <template #pager></template> -->
        </vxe-grid>
      </div>
      <!-- <a-pagination
        :current="1"
        :page-size-options="['5', '10', '15', '20', '50', '100', '150', '200']"
        :page-size="10"
        :total="20"
        showSizeChanger
        showQuickJumper>
      </a-pagination> -->
    </template>
    <template #drawer v-if="visible">
      <a-form
        ref="formRef"
        :model="modelRef"
        :rules="rulesRef"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item
          label="类型"
          required
        >
          <a-radio-group v-model:value="modelRef.type" @change="changeType">
            <a-radio-button v-for="item in [0, 1, 2]" :key="item" :value="item">{{enumMenuType(item)}}</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="modelRef.type === 2"
          label="按钮类型"
          required
        >
          <a-radio-group v-model:value="btnType" @change="changeBtnType">
            <a-radio-button :value="1">基本按钮</a-radio-button>
            <a-radio-button :value="2">路由按钮</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="名称"
          name="name"
        >
          <a-input placeholder="填写菜单名称" v-model:value="modelRef.name" />
        </a-form-item>
        <a-form-item
          label="上级菜单"
          name="parentId"
        >
          <a-tree-select
            v-model:value="modelRef.parentId"
            show-search
            class="rd-w-100"
            placeholder="选择上级菜单,不选视为根目录"
            tree-default-expand-all
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="menuTree"
            :replace-fields="{ title:'name', value: 'menuId' }"
          ></a-tree-select>
        </a-form-item>
        <a-form-item
          v-if="modelRef.type > 0 && btnType > 1"
          label="导航路径"
          name="url"
        >
          <a-input placeholder="填写导航路径(/user/list)" v-model:value="modelRef.url" />
        </a-form-item>
        <a-form-item
          v-if="modelRef.type > 0 && btnType > 1"
          label="页面路径"
          name="pageUrl"
        >
          <a-input placeholder="填写页面路径(/user/List)" v-model:value="modelRef.pageUrl" />
        </a-form-item>
        <a-form-item
          label="菜单高亮key"
          name="key"
        >
          <a-input placeholder="用.分隔, 如: user.list" v-model:value="modelRef.key" />
        </a-form-item>
        <a-form-item
          v-if="modelRef.type < 2"
          label="图标"
          name="icon"
        >
          <a-radio-group
            class="rd-w-100"
            size="small"
            v-model:value="modelRef.icon"
          >
            <a-radio-button v-for="icon in iconNames" :key="icon" :value="icon">
              <IconAntdv :icon="icon" />
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="授权标识"
          name="perms"
        >
          <a-input placeholder="用冒号分隔, 如: user:list" v-model:value="modelRef.perms" />
        </a-form-item>
        <a-form-item
          label="排序号"
          name="orderNum"
        >
          <a-input-number placeholder="填写排序号" v-model:value="modelRef.orderNum" :min="0" :precision="0" />
        </a-form-item>
        <div class="rd-box-center">
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </div>
      </a-form>
    </template>
  </layout-drawer-list>
</template>

<script>
import { ref, reactive, onMounted, toRaw } from 'vue'
import { cloneDeep } from 'lodash'
import { Enum } from '@/utils'
import LayoutDrawerList from '@/layout/LayoutDrawerList.vue'
import mainMenuList from '@/composables/system/mainMenuList'
// api
// import { fetchMenuDelete } from '@/api'
import { fetchMenuCreate, fetchMenuUpdate, fetchMenuDelete } from '@/api'

const { enumMenuType, enumModifyType, enumSubjectId } = Enum

// 表单校验规则
const rulesRef = {
  name: [
    {
      required: true,
      message: '填写菜单名称',
      trigger: 'blur'
    }
  ],
  parentId: [
    {
      required: true,
      message: '选择父级',
      trigger: 'change'
    }
  ],
  url: [
    {
      required: true,
      message: '填写导航路径',
      trigger: 'blur'
    }
  ],
  orderNum: [
    {
      type: 'number',
      required: true,
      message: '填写排序号',
      trigger: 'change'
    }
  ],
  icon: [
    {
      required: true,
      message: '选择图标',
      trigger: 'change'
    }
  ],
  key: [
    {
      required: true,
      message: '填写菜单高亮key',
      trigger: 'blur'
    }
  ],
  pageUrl: [
    {
      required: true,
      message: '填写调用页面路径',
      trigger: 'blur'
    }
  ]
}

export default {
  components: {
    LayoutDrawerList
  },
  setup () {
    const subjectId = ref('1')
    const visible = ref(false)
    const drawerType = ref('create')
    const { tableTree, menuTree, getMenuList } = mainMenuList
    // 表格配置
    const gridOptions = reactive({
      border: 'inner',
      align: 'center',
      'auto-resize': true,
      'highlight-hover-row': true,
      'max-height': '100%',
      'row-id': 'id',
      'tree-config': { children: 'children', expandAll: true },
      columns: [
        { type: 'seq', treeNode: true },
        { field: 'icon', title: '图标', slots: { default: 'icon' } },
        { field: 'name', title: '名称' },
        { field: 'perms', title: '权限', showOverflow: true },
        { field: 'type', title: '类型', slots: { default: 'type' } },
        { field: 'url', title: '菜单路径', showOverflow: true },
        { field: 'pageUrl', title: '页面路径', showOverflow: true },
        { field: 'orderNumber', title: '排序号' },
        { title: '操作', slots: { default: 'modify' } }
      ]
    })
    // 表单配置
    const formRef = ref()
    const btnType = ref(2)
    const defaultModelRef = reactive({
      subjectId: subjectId.value,
      type: 0,
      name: '',
      parentId: '0',
      url: '',
      perms: '',
      orderNum: 0,
      icon: '',
      key: '',
      pageUrl: ''
    })
    const modelRef = ref(defaultModelRef)

    /**
     * 切换专题
     */
    const changeSubjectId = () => {
      defaultModelRef.subjectId = subjectId.value
      getMenuList(subjectId.value)
    }

    /**
     * 提交
     */
    const onSubmit = () => {
      formRef.value.validate().then(async () => {
        let submitRes
        const info = toRaw(modelRef.value)
        if (info.type === 0 || (info.type === 2 && btnType.value === 1)) {
          info.url = ''
          info.pageUrl = ''
        }
        if (drawerType.value === 'create') {
          submitRes = await fetchMenuCreate(info)
        } else {
          submitRes = await fetchMenuUpdate(info)
        }
        if (submitRes.code === 0) {
          visible.value = false
          getMenuList(subjectId.value)
          return
        }
        console.log(submitRes)
      }).catch(err => {
        console.log('error', err)
      })
    }
    /**
     * 提交删除
     */
    const onSubmitDelete = async row => {
      const staticRow = toRaw(row)
      const deleteRes = await fetchMenuDelete(staticRow.menuId)
      console.log(deleteRes)
      if (deleteRes.code === 0) {
        getMenuList(subjectId.value)
        return
      }
      console.log(deleteRes)
    }
    /**
     * 类型切换
     */
    const changeType = () => {
      formRef.value.resetFields()
      if (modelRef.value.type === 2) {
        btnType.value = 1
      } else {
        btnType.value = 2
      }
    }
    /**
     * 类型切换
     */
    const changeBtnType = () => {
      formRef.value.resetFields()
    }
    /**
     * 打开菜单抽屉
     */
    const openDrawer = (type, row) => {
      if (row) {
        modelRef.value = cloneDeep(row)
        delete modelRef.value.children
      } else {
        modelRef.value = defaultModelRef
      }
      if (modelRef.value.type === 2) {
        modelRef.value.url ? btnType.value = 2 : btnType.value = 1
      }
      drawerType.value = type
      visible.value = true
    }

    onMounted(getMenuList(subjectId.value))
    return {
      subjectId,
      visible,
      formRef,
      btnType,
      enumMenuType,
      enumModifyType,
      enumSubjectId,
      drawerType,
      tableTree,
      menuTree,
      gridOptions,
      labelCol: {
        lg: 9,
        xl: 7,
        xxl: 4
      },
      wrapperCol: {
        lg: 15,
        xl: 17,
        xxl: 20
      },
      modelRef,
      rulesRef,
      changeSubjectId,
      onSubmit,
      onSubmitDelete,
      getMenuList,
      changeType,
      changeBtnType,
      openDrawer,
      iconNames: ['AppstoreOutlined', 'AudioOutlined']
    }
  }
}
</script>
